<template>
  <el-dialog
    v-model="visible"
    title="催单提醒"
    :width="isMobile ? '90%' : '400px'"
    :center="true"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="urgent-notification-dialog"
    :z-index="9999"
  >
    <div class="urgent-content">
      <div class="urgent-icon">
        <el-icon :size="48" color="#ff4949">
          <Bell />
        </el-icon>
      </div>
      
      <div class="urgent-message">
        <h3>{{ title }}</h3>
        <p>{{ message }}</p>
      </div>

      <div class="countdown-bar">
        <div 
          class="countdown-progress" 
          :style="{ width: `${progressWidth}%` }"
        ></div>
      </div>
      
      <div class="countdown-text">
        {{ Math.ceil(remainingTime / 1000) }} 秒后自动关闭
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" type="primary">
          我知道了
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { Bell } from '@element-plus/icons-vue';

interface Props {
  visible: boolean;
  title?: string;
  message?: string;
  duration?: number; // 持续时间（毫秒）
  enableVibration?: boolean; // 是否启用震动
}

const props = withDefaults(defineProps<Props>(), {
  title: '催单提醒',
  message: '您有新的催单消息，请及时处理订单！',
  duration: 10000, // 默认10秒
  enableVibration: true
});

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'close': [];
}>();

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const remainingTime = ref(props.duration);
const progressWidth = computed(() => {
  return (remainingTime.value / props.duration) * 100;
});

const isMobile = computed(() => {
  return window.innerWidth <= 768;
});

let countdownTimer: number | null = null;

// 震动功能
const triggerVibration = () => {
  if (props.enableVibration && 'vibrate' in navigator) {
    // 震动模式：短震-停-短震-停-长震
    navigator.vibrate([200, 100, 200, 100, 500]);
  }
};

// 播放提示音（如果需要的话）
const playNotificationSound = () => {
  try {
    // 创建一个简单的提示音
    const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
    const oscillator = audioContext.createOscillator();
    const gainNode = audioContext.createGain();
    
    oscillator.connect(gainNode);
    gainNode.connect(audioContext.destination);
    
    oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
    oscillator.frequency.setValueAtTime(1000, audioContext.currentTime + 0.1);
    
    gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.5);
  } catch (error) {
    console.warn('无法播放提示音:', error);
  }
};

// 开始倒计时
const startCountdown = () => {
  remainingTime.value = props.duration;
  
  countdownTimer = window.setInterval(() => {
    remainingTime.value -= 100;
    
    if (remainingTime.value <= 0) {
      handleClose();
    }
  }, 100);
};

// 停止倒计时
const stopCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
};

// 关闭通知
const handleClose = () => {
  stopCountdown();
  visible.value = false;
  emit('close');
};

// 监听显示状态变化
watch(visible, (newVisible) => {
  if (newVisible) {
    // 显示时启动倒计时并触发震动和提示音
    startCountdown();
    triggerVibration();
    playNotificationSound();
  } else {
    // 隐藏时停止倒计时
    stopCountdown();
  }
});

onUnmounted(() => {
  stopCountdown();
});
</script>

<style scoped>
.urgent-notification-dialog {
  --el-dialog-border-radius: 12px;
}

:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(255, 73, 73, 0.3);
  animation: urgentShake 0.5s ease-in-out;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #ff6b6b, #ff4949);
  color: white;
  padding: 20px 20px 0;
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.urgent-content {
  text-align: center;
  padding: 10px 0;
}

.urgent-icon {
  margin-bottom: 16px;
  animation: urgentPulse 1s infinite;
}

.urgent-message h3 {
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.urgent-message p {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 20px 0;
}

.countdown-bar {
  width: 100%;
  height: 4px;
  background: #e4e7ed;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 12px;
}

.countdown-progress {
  height: 100%;
  background: linear-gradient(90deg, #ff6b6b, #ff4949);
  border-radius: 2px;
  transition: width 0.1s linear;
}

.countdown-text {
  color: #909399;
  font-size: 12px;
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #ff6b6b, #ff4949);
  border: none;
  padding: 10px 24px;
  border-radius: 20px;
  font-weight: 600;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #ff5252, #e53935);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 73, 73, 0.4);
}

/* 动画效果 */
@keyframes urgentShake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
  20%, 40%, 60%, 80% { transform: translateX(2px); }
}

@keyframes urgentPulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

/* 移动端适配 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    margin: 5vh auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .urgent-message h3 {
    font-size: 18px;
  }
  
  .urgent-message p {
    font-size: 13px;
  }
}
</style>
